package com.rp.common.exception.handler;

import com.rp.common.result.ResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 类说明:
 *
 * @author ****
 * @date 2020-12-22 11:14  新建
 */
@Slf4j
@Order(97)
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 校验错误拦截处理
     *
     * @param exception 错误信息集合
     * @return 错误信息
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultDTO validationBodyException(MethodArgumentNotValidException exception) {
        BindingResult result = exception.getBindingResult();
        String message = "";
        if (result.hasErrors()) {
            List<ObjectError> errors = result.getAllErrors();
            if (errors.size() > 0) {
                FieldError fieldError = (FieldError) errors.get(0);
                message = "请检查参数: 对象{" + fieldError.getObjectName() + "}, 字段{" + fieldError.getField() +
                        "}, 错误信息{" + fieldError.getDefaultMessage() + "}";
                log.error(message);
            }
        }
        return ResultDTO.PARAM_ERROR().message(message);
    }

    /**
     * 参数类型转换错误
     *
     * @param exception 错误
     * @return 错误信息
     */
    @ExceptionHandler(HttpMessageConversionException.class)
    public ResultDTO parameterTypeException(HttpMessageConversionException exception) {
        log.error(exception.getCause().getLocalizedMessage());
        return ResultDTO.PARAM_ERROR().message("类型转换错误");
    }

    //必要参数不存在
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResultDTO parameterTypeException(MissingServletRequestParameterException exception) {
        log.error(exception.getCause().getLocalizedMessage());
        return ResultDTO.PARAM_ERROR().message(exception.getCause().getLocalizedMessage());
    }


}